package cn.jiedh.app.meiweidk.newpeopleproduct;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import org.xutils.ex.HttpException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.MyWebActivity;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.EmptyRecyclerView;
import cn.jiedh.app.meiweidk.Utils.UI.StateLayout;
import cn.jiedh.app.meiweidk.Utils.UI.VerticalSpaceItemDecoration;
import cn.jiedh.app.meiweidk.Utils.config.ConfigUtils;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.DensityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.NumUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.baseadapter.BaseAdapter;
import cn.jiedh.app.meiweidk.baseadapter.BaseViewHolder;
import cn.jiedh.app.meiweidk.homepage.NewProductData;
import cn.jiedh.app.meiweidk.homepage.category.CategoryActivity;
import cn.jiedh.app.meiweidk.loan.LoanDetailActivity;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;

/**
 * @name： 新人专享产品列表
 * @author： 周毅
 * @phone： 15826080712
 * @createTime： 2017/12/7
 * @modifyTime： 2017/12/7
 * @explain：
 */

public class NewPeopleProductListActivity extends BaseActivity {
    @BindView(R.id.bar_img_back)
    ImageView barImgBack;
    @BindView(R.id.bar_tv_close)
    TextView barTvClose;
    @BindView(R.id.bar_tv_other)
    TextView barTvOther;
    @BindView(R.id.tv)
    TextView tv;
    @BindView(R.id.bar_tv_title)
    TextView barTvTitle;
    @BindView(R.id.bar_img_more)
    ImageView barImgMore;
    @BindView(R.id.title_layout)
    LinearLayout titleLayout;
    @BindView(R.id.tvmoney)
    TextView tvmoney;
    @BindView(R.id.setmoney)
    TextView setmoney;
    @BindView(R.id.newpeoplelistview)
    EmptyRecyclerView newpeoplelistview;
    @BindView(R.id.empty_nn_pic)
    ImageView emptyNnPic;
    @BindView(R.id.empty_nn_btn)
    TextView emptyNnBtn;
    String money;
    @BindView(R.id.statelayout)
    StateLayout statelayout;
    @BindView(R.id.smartrefreshLayout)
    SmartRefreshLayout smartrefreshLayout;
    @BindView(R.id.rl_moneytitle)
    LinearLayout rlMoneytitle;
    private List<NewProduct> newProductList = new ArrayList<>();
    BaseAdapter<NewProduct> adapter;
    private int pageNo = 1;

    private View emptyView;
    OptionsPickerView showMoneyPop;
    @Override
    protected int getLayoutView() {
        return R.layout.newpeopleplist;
    }

    @Override
    protected void initView(View view) {
        barTvTitle.setText("新人专享");

        money = SPUtils.getMoney();
        L.i("new_money", money + "-------------");
        tvmoney.setText(NumUtils.getTwoDecimal(Double.parseDouble(money)));
        statelayout.setOnNoClick(view12 -> smartrefreshLayout.autoRefresh());
    }

    /**
     * 新人专享数据接口
     */
    private void Newexclusive() {
        Map<String, Object> map = new HashMap<>();
        map.put("pageNo", pageNo);
        map.put("pageSize", "10");
        map.put("money", money);
        request(activity, UrlUtils.GetNewExclusiveProductList, map, true, new ResponseSuccess<NewProductData>() {
            @Override
            public void onRequestSucceed(BaseResponse<NewProductData> response) {
                if (response.getCode() == 0) {
                    if (response.getData() != null && response.getData().getDataList() != null) {
                        rlMoneytitle.setVisibility(View.VISIBLE);
                        if (pageNo == 1) {
                            newProductList.clear();
                        }
                        newpeoplelistview.setEmptyView(emptyView);
                        newProductList.addAll(response.getData().getDataList());
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    rlMoneytitle.setVisibility(View.GONE);
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                rlMoneytitle.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    protected void initData() {
        emptyView = findViewById(R.id.emptyview);
        emptyNnPic.setImageResource(R.mipmap.mylljl);
        emptyNnBtn.setText("暂无产品");
        adapter = new BaseAdapter<NewProduct>(activity, R.layout.layout_home_groom, newProductList) {
            @Override
            public void convert(BaseViewHolder holder, NewProduct newProduct, int position) {
                holder.setImageUrl(R.id.home_groom_iv, newProduct.getImgUrl());
                holder.setText(R.id.home_groom_name, newProduct.getName());
                holder.setText(R.id.loan_advert, newProduct.getAdver());
                String moneyMin = newProduct.getMoneyMin() + "";
                String moneyMax = newProduct.getMoneyMax() + "";
                if (moneyMin.length() >= 6) {
                    moneyMin = newProduct.getMoneyMin() / 10000 + "";
                } else {
                    moneyMin = newProduct.getMoneyMin() + "";
                }
                if (moneyMax.length() >= 6) {
                    moneyMax = newProduct.getMoneyMax() / 10000 + "万";
                } else {
                    moneyMax = newProduct.getMoneyMax() + "";
                }
                holder.setText(R.id.home_groom_ad, moneyMin + "-" + moneyMax);

                holder.setText(R.id.loan_daily_rate,NumUtils.getTwoDecimal(newProduct.getRate())  + "%");
                holder.setText(R.id.rate_type_tv, "参考"+newProduct.getRateTypeStr()+"利率");

                holder.setText(R.id.loan_success_rate, newProduct.getSuccessRate()  + "%");
                holder.getView(R.id.new_product_).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MobclickAgent.onEvent(activity,"newbie_list");
                        SPUtils.saveBuried("click","0","新人专享-更多推荐-"+newProduct.getName(),""
                                ,"新人专享-更多推荐-列表","","",newProduct.getProductId()+"");
                        Bundle bundle = new Bundle();
                        bundle.putInt("productId", newProduct.getProductId());
                        ActivityUtil.next(activity, LoanDetailActivity.class, bundle);
                    }
                });

                TextView goApply_tv=holder.getView(R.id.goApply_tv);
                goApply_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        apply(newProduct.getProductId(),newProduct.getApplyUrl(),newProduct.getName());
                    }
                });
            }
        };
        newpeoplelistview.setLayoutManager(new LinearLayoutManager(this));

        newpeoplelistview.addItemDecoration(new VerticalSpaceItemDecoration(DensityUtil.dip2px(NewPeopleProductListActivity.this,10),false));

        newpeoplelistview.setAdapter(adapter);
        smartrefreshLayout.autoRefresh();
        smartrefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        refreshAndLoad();
        initPop();
    }



    /**
     * 统计并跳转
     *
     * @param productId
     * @param applyUrl
     * @param loanTitle
     */
    private void apply(int productId, String applyUrl, String loanTitle) {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("productId", productId + "");
        request(UrlUtils.ADDBROWSE, map, false, new ResponseSuccess<String>() {
            @Override
            public void onRequestSucceed(BaseResponse response) {
                dismissLoadingDialog();
                if (0 == response.getCode()) {
                    Bundle bundle = new Bundle();
                    bundle.putString("url", applyUrl);
                    bundle.putString("title", loanTitle);
                    Intent intent = new Intent(NewPeopleProductListActivity.this, MyWebActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 1);
                } else {
                    T.showShort(response.getMessage());
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                T.show(msg);
                dismissLoadingDialog();
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    List<String> moneylist = new ArrayList<>();

    private void initPop() {
        showMoneyPop = new OptionsPickerView.Builder(this, (options1, options2, options3, v) -> {
            if (SPUtils.getmoneylist().size() > 0) {
                tvmoney.setText("¥ "+NumUtils.getTwoDecimal(SPUtils.getmoneylist().get(options1).getValue()));
            }
            money= SPUtils.getmoneylist().get(options1).getValue()+"";
            SPUtils.saveToApp(activity, ConfigUtils.MONEY, SPUtils.getmoneylist().get(options1).getValue()+"");
            SPUtils.saveToApp(activity,SPUtils.getPhone(),SPUtils.getmoneylist().get(options1).getValue()+"");
            smartrefreshLayout.autoRefresh();
        }).setOutSideCancelable(false)
                .setDividerColor(Color.parseColor("#DADADA"))
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setTitleText("设置金额")
                .setTitleColor(Color.BLACK)
                .setTitleSize(18)
                .setCancelColor(Color.BLACK)
                .build();
        if (SPUtils.getmoneylist().size() > 0) {
            for (int i = 0; i < SPUtils.getmoneylist().size(); i++) {
                if (i==SPUtils.getmoneylist().size()-1){
                    moneylist.add(SPUtils.getmoneylist().get(i).getName());
                }else{
                    moneylist.add(SPUtils.getmoneylist().get(i).getName() + "元");
                }
            }
        }
        showMoneyPop.setPicker(moneylist);
    }

    private void refreshAndLoad() {
        smartrefreshLayout.setOnRefreshListener(refreshLayout -> refreshLayout.getLayout().postDelayed(() -> {
            pageNo = 1;
//            stateLayout.netviewGone();
            Newexclusive();
            refreshLayout.finishRefresh();
        }, 2000));
        smartrefreshLayout.setOnLoadmoreListener(refreshLayout -> {
            refreshLayout.getLayout().postDelayed(() -> {
                pageNo++;
                Newexclusive();
                refreshLayout.finishLoadmore();
            }, 2000);

        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.bar_img_back, R.id.setmoney, R.id.empty_nn_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bar_img_back:
                finish();
                break;
            case R.id.setmoney:
                if (showMoneyPop != null) {
                    showMoneyPop.show();
                }
                break;
            case R.id.empty_nn_btn:
                break;
        }
    }
}
